package com.client.discovery;

import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;

/**
 * zk服务发现接口
 *
 * @author 陶肖寅
 * @version V1.0
 * @Package com.client.discovery
 * @email fromlx@126.com
 * @date 2020-04-07 13:19
 * @Copyright © 2020-2021 城云科技(中国)有限公司
 */
public class ServiceDiscovery {
    private volatile List<String> dataList = new ArrayList<String>();
    private static String ZK_REGISTRY_PATH="/lg-netty";
    private String registryAddress;

    public ServiceDiscovery(String registryAddress) {
        this.registryAddress = registryAddress;
        ZkClient client = connectServer();
        if (client != null) {
            watchNode(client);
        }
    }

    public String discover() {
        String data = null;
        int size = dataList.size();
        if (size > 0) {
            if (size == 1) {
                data = dataList.get(0);
            } else {
                //随机获取其中的一个
                data = dataList.get(ThreadLocalRandom.current().nextInt(size));
            }
        }
        return data;
    }

    /**
     * 建立zookeeper连接
     * @return
     */
    private ZkClient connectServer() {
        ZkClient client = null;
        try {
            client = new ZkClient(registryAddress, 5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }

    /**
     * 将数据添加到zk中
     * @param client
     */
    private void watchNode(final ZkClient client) {
        try {
            List<String> nodeList = client.getChildren(ZK_REGISTRY_PATH);
            List<String> dataList = new ArrayList<String>();
            for (String node : nodeList) {
                Object data = client.readData(ZK_REGISTRY_PATH+"/"+node);
                if(data!=null){
                    dataList.add((String)data);
                }
            }
            this.dataList = dataList;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
